
const log4js = require('log4js');
const methods = ["trace", "debug", "info", "warn", "error", "fatal", "mark"]

module.exports = () => {
    return async (ctx, next) => {
        const contextLogger = {}
        const start = Date.now()
        log4js.configure({
            appenders: {
                koa2learn: {
                    type: 'dateFile', // 日志类型
                    filename: `./logs/koa2learn`,  // 输出的文件名
                    pattern: 'yyyy-MM-dd.log',  // 文件名增加后缀
                    alwaysIncludePattern: true   // 是否总是有后缀名
                }
            },
            categories: {
                default: {
                    appenders: ['koa2learn'],
                    level: 'info'
                }
            }
        });
        const logger = log4js.getLogger('koa2learn');
        // 循环methods将所有方法挂载到ctx 上
        methods.forEach((method, i) => {
            contextLogger[method] = (message) => {
                logger[method](message)
            }
        })
        ctx.log = contextLogger;
        debugger
        await next();
        const responseTime = Date.now() - start;
        logger.info(`响应时间为${responseTime/1000}s`);
    }
}
